<!doctype html>
<html>
  <head>
    <title>认证测试</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        margin: 20px;
      }
      .test-result {
        margin: 10px 0;
        padding: 10px;
        border-radius: 4px;
      }
      .success {
        background-color: #d4edda;
        border: 1px solid #c3e6cb;
        color: #155724;
      }
      .error {
        background-color: #f8d7da;
        border: 1px solid #f5c6cb;
        color: #721c24;
      }
      .info {
        background-color: #d1ecf1;
        border: 1px solid #b8daff;
        color: #0c5460;
      }
      button {
        margin: 5px;
        padding: 8px 16px;
      }
      pre {
        background: #f8f9fa;
        padding: 10px;
        border-radius: 4px;
        overflow-x: auto;
      }
    </style>
  </head>
  <body>
    <h1>认证状态测试</h1>
    <div id="results"></div>

    <button onclick="testLocalStorage()">测试 LocalStorage</button>
    <button onclick="testBackendHealth()">测试后端健康</button>
    <button onclick="testAuthAPI()">测试认证API</button>
    <button onclick="testLogin()">测试登录</button>
    <button onclick="clearAll()">清除所有</button>

    <script>
      const results = document.getElementById('results')

      function addResult(message, type = 'info') {
        const div = document.createElement('div')
        div.className = `test-result ${type}`
        div.innerHTML = message
        results.appendChild(div)
      }

      function testLocalStorage() {
        addResult('<strong>测试 LocalStorage</strong>')
        const token = localStorage.getItem('novel_app_token')
        if (token) {
          addResult(`Token 存在: ${token.substring(0, 50)}...`, 'success')
          try {
            const payload = JSON.parse(atob(token.split('.')[1]))
            addResult(
              `Token 载荷: <pre>${JSON.stringify(payload, null, 2)}</pre>`,
              'info'
            )
            const now = Math.floor(Date.now() / 1000)
            if (payload.exp && payload.exp < now) {
              addResult('Token 已过期', 'error')
            } else {
              addResult(
                `Token 有效，过期时间: ${new Date(payload.exp * 1000).toLocaleString()}`,
                'success'
              )
            }
          } catch (e) {
            addResult(`Token 解析错误: ${e.message}`, 'error')
          }
        } else {
          addResult('没有找到 Token', 'error')
        }
      }

      async function testBackendHealth() {
        addResult('<strong>测试后端健康状态</strong>')
        try {
          const response = await fetch('http://localhost:3000/health')
          const data = await response.json()
          addResult(
            `后端健康状态: <pre>${JSON.stringify(data, null, 2)}</pre>`,
            'success'
          )
        } catch (error) {
          addResult(`后端健康检查失败: ${error.message}`, 'error')
        }
      }

      async function testAuthAPI() {
        addResult('<strong>测试认证API</strong>')
        const token = localStorage.getItem('novel_app_token')

        if (!token) {
          addResult('没有 Token，无法测试认证API', 'error')
          return
        }

        try {
          const response = await fetch(
            'http://localhost:3000/api/auth/profile',
            {
              headers: {
                Authorization: `Bearer ${token}`,
                'Content-Type': 'application/json',
              },
              credentials: 'include',
            }
          )

          addResult(
            `响应状态: ${response.status} ${response.statusText}`,
            response.ok ? 'success' : 'error'
          )

          const data = await response.json()
          addResult(
            `响应数据: <pre>${JSON.stringify(data, null, 2)}</pre>`,
            response.ok ? 'success' : 'error'
          )
        } catch (error) {
          addResult(`认证API调用失败: ${error.message}`, 'error')
        }
      }

      async function testLogin() {
        addResult('<strong>测试登录流程</strong>')
        try {
          const response = await fetch('http://localhost:3000/api/auth/login', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            credentials: 'include',
            body: JSON.stringify({
              email: 'admin@example.com',
              password: 'admin123',
            }),
          })

          const data = await response.json()
          addResult(
            `登录响应: <pre>${JSON.stringify(data, null, 2)}</pre>`,
            response.ok ? 'success' : 'error'
          )

          if (response.ok && data.data && data.data.token) {
            localStorage.setItem('novel_app_token', data.data.token)
            addResult('Token 已保存到 LocalStorage', 'success')
          }
        } catch (error) {
          addResult(`登录测试失败: ${error.message}`, 'error')
        }
      }

      function clearAll() {
        localStorage.removeItem('novel_app_token')
        results.innerHTML = ''
        addResult('已清除所有数据', 'success')
      }

      // 页面加载时自动运行基础测试
      window.onload = function () {
        testLocalStorage()
        testBackendHealth()
      }
    </script>
  </body>
</html>
